package com.intelligent.bot.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.bot.base.exception.E;
import com.intelligent.bot.base.result.B;
import com.intelligent.bot.dao.UserDao;
import com.intelligent.bot.model.User;
import com.intelligent.bot.model.req.*;
import com.intelligent.bot.model.res.LoginUserRes;
import com.intelligent.bot.utils.sys.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = E.class)
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {


    @Override
    public B<LoginUserRes> adminLogin(LoginUserReq req)  {
        List<User> list = this.lambdaQuery()
                .eq(User::getPhone, req.getPhone())
                .eq(User::getPassword, SecureUtil.md5(req.getPassword()))
                .in(User::getType, 1,2)
                .list();
        if (list == null || list.isEmpty()) {
            return B.finalBuild("用户名或密码错误");
        }
        User user = list.get(0);
        String token = JwtUtil.createToken(user);
        LoginUserRes res = new LoginUserRes();
        res.setToken(token);
        res.setNickName(user.getNickName());
        res.setId(user.getId());
        return B.okBuild(res);
    }

    @Override
    public B<Void> adminAdd(AdminAddReq req) {
        Long count = this.lambdaQuery().eq(User::getPhone, req.getPhone()).count();
        if(count > 0){
            throw new E("手机号已存在");
        }
        User user = BeanUtil.copyProperties(req, User.class);
        user.setType(2);
        user.setPassword(SecureUtil.md5(req.getPassword()));
        this.save(user);
        return B.okBuild();
    }

    @Override
    public B<Void> update(AdminUpdateReq req) {
        Long count = this.lambdaQuery().eq(User::getPhone, req.getPhone()).ne(User::getId, req.getId()).count();
        if(count > 0){
            throw new E("账号已存在已存在");
        }
        User user = BeanUtil.copyProperties(req, User.class);
        if(null != req.getPassword()){
            user.setPassword(SecureUtil.md5(req.getPassword()));
        }
        this.updateById(user);
        return B.okBuild();
    }

    @Override
    public B<Page<User>> getAdminList(UserGetListReq req) {
        Page<User> page = new Page<>(req.getPageNumber(),req.getPageSize());
        return B.okBuild(baseMapper.getList(page, req));
    }

}
